<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */

    /**
     * Defines the model to validate.
     *
     * @package    kassiop.core
     * @subpackage models
     *
     * @author NairuS
     * @version 1.2 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     */
    abstract class Model implements iValidate, Serializable
    {
        /**
         * Create an instance of Model
         */
        public function __construct( ValueObject $vo )
        {
            $this->setExcludeFields( array( Model::EXPLICIT_TYPE ) ) ;
            $this->vo = $vo ;
            $this->configure() ;
        }

        /**
         * Defines the id field.
         *
         * @var string
         */
        const ID_FIELD      = 'id' ;

        /**
         * Defines the _explicitType field.
         *
         * @var string
         */
        const EXPLICIT_TYPE = '_explicitType' ;

        /**
         * Defines the errors serialized.
         *
         * @var string
         */
        public $serialized ;

        /**
         * The vo of the model to validate.
         *
         * @var ValueObject
         */
        public $vo ;

        /**
         * Defines the errors of the model validation.
         *
         * @var array
         */
        private $errors = array() ;

        /**
         * Excludes some model fields of the validation.
         *
         * @var array
         */
        private $excludeFields = array() ;

        /**
         * Defines the global errors of the model validation.
         *
         * @var array
         */
        private $globalErrors = array() ;

        /**
         * Defines the postValidators of the model
         *
         * @var array
         */
        private $postValidators = array() ;

        /**
         * Defines the schemaValidators of the model
         *
         * @var array of FieldsCompareValidator
         */
        private $schemaValidators = array() ;

        /**
         * Defines the validators of the model
         *
         * @var array
         */
        private $validators = array() ;

        /**
         * Add a shema validator
         *
         * @param  FieldsCompareValidator $validator
         * @return void
         */
        public function addSchemaValidator(FieldsCompareValidator  $validator)
        {
            array_push( $this->schemaValidators, $validator );
        }

        /**
         * (non-PHPdoc)
         * @see kassiop/core/models/iValidable#hasErrors()
         */
        public function hasErrors()
        {
            return count( $this->getErrors() ) > 0 || count( $this->globalErrors ) > 0;
        }

        /**
         * Returns all the errors of the model.
         *
         * @return array
         */
        public function getErrors()
        {
            return $this->errors ;
        }

        /**
         * Returns the global errors of the model.
         *
         * @return array of FieldsCompareValidator
         */
        public function getGlobalErrors()
        {
            return $this->globalErrors;
        }

        /**
         * Returns an ErrorFieldVO of the model.
         *
         * @param  string  $name
         * @return ErrorFieldVO
         */
        public function getError( $name )
        {
            if( $this->hasErrors() )
            {
                foreach( $this->getErrors() as $e )
                {
                    if( $e instanceof ErrorFieldVO && $e->field == $name)
                    {
                        return $e ;
                    }
                }
            }
            return null;
        }

        /**
         * Returns the excludeFields array.
         *
         * @return array
         */
        public function getExcludeFields()
        {
            return $this->excludeFields ;
        }

        /**
         * Returns the all the validators of the model.
         *
         * @return array
         */
        public function getPostValidators()
        {
            return $this->postValidators ;
        }

        /**
         * Returns the validator for the field passed-in.
         *
         * @param string $field
         * @return BaseValidator
         */
        public function getPostValidator( $field )
        {
            return isset( $this->postValidators[$field] ) && $this->postValidators[$field] instanceof BaseValidator ? $this->postValidators[$field] : null ;
        }

        /**
         * Returns the validator for the field passed-in.
         *
         * @param string $field
         * @return BaseValidator
         */
        public function getValidator( $field )
        {
            return isset( $this->validators[$field] ) && $this->validators[$field] instanceof BaseValidator ? $this->validators[$field] : null ;
        }

        /**
         * Returns the all the schema validators of the model.
         *
         * @return array of FieldsCompareValidator
         */
        public function getSchemaValidators()
        {
            return $this->schemaValidators ;
        }

        /**
         * Returns the all the validators of the model.
         *
         * @return array
         */
        public function getValidators()
        {
            return $this->validators ;
        }

        /**
         * Returns the ValueObject of the model
         * Inherit this method to return the right type of ValueObject
         *
         * @return ValueObject
         */
        public function getVO()
        {
            return $this->vo;
        }

        /**
         * Returns true if the ValueObject of the model is a new one.
         *
         * @return boolean
         */
        public function isNew()
        {
            return !$this->vo instanceof ValueObject || $this->vo->id == null;
        }
        /**
         * Merges the excludeFields array.
         *
         * @param  $fields
         * @return void
         */
        public function setExcludeFields( array $fields )
        {
            $this->excludeFields = array_merge( $this->excludeFields, $fields ) ;
        }

        /**
         * Set an option of the validator reference passed-in
         *
         * @param string        $name
         * @param mixed         $value
         * @param BaseValidator $validator
         */
        public function setOption( $name, $value, BaseValidator &$validator )
        {
            $validator->setOption( $name, $value );
        }

        /**
         * Sets a postValidator for a field in the collection.
         *
         * @param  string        $field
         * @param  BaseValidator $validator
         * @return void
         */
        public function setPostValidator( $field, BaseValidator $validator )
        {
            $this->postValidators[$field] = $validator ;
        }

        /**
         * Sets all the validators of the model.
         *
         * @param array $validators
         */
        public function setPostValidators( array $validators )
        {
            $this->postValidators = $validators ;
        }

        /**
         * Sets the validator for the field passed-in.
         *
         * @param  string        $field
         * @param  BaseValidator $validator
         * @return void
         */
        public function setValidator( $field, BaseValidator $validator )
        {
            $this->validators[$field] = $validator ;
        }

        /**
         * Sets all the schema validators of the model.
         *
         * @param  array $validators array of FieldsCompareValidator
         * @return void
         * @throws InvalidArgumentException
         */
        public function setSchemaValidators( array $validators )
        {
            foreach( $validators as $validator )
            {
                if( $validator instanceof FieldsCompareValidator )
                {
                    $this->addSchemaValidator( $validator );
                }
                else
                {
                    throw new InvalidArgumentException('The validators must be an instance of FieldsCompareValidator.');
                }
            }
        }

        /**
         * Sets all the validators of the model.
         *
         * @param array $validators
         */
        public function setValidators( array $validators )
        {
            $this->validators = $validators ;
        }

        /**
         * Serializes the errors of the model.
         *
         * @return string of the model's errors serialized.
         */
        public function serialize()
        {
            return $this->serialized = serialize( $this->getErrors() ) ;
        }

        /**
         * Unserializes the errors of the model.
         *
         * @return array of the model's errors unserialized.
         */
        public function unserialize( $serialized )
        {
            return unserialize( $serialized );
        }

        /**
         * Validates all the model fields.
         *
         * @see kassiop/core/models/iValidable#validate()
         * @return true or false.
         */
        public function validate()
        {
            $this->beforeValidate();
            $reflection = new ReflectionClass( $this->vo ) ;
            foreach( $reflection->getProperties() as $prop )
            {
                $propName = $prop->name ;

                // launch all the validators.
                if( !in_array( $propName, $this->getExcludeFields() ) )
                {
                    try
                    {
                        // try the validator of the property.
                        $validator = $this->getValidator( $propName ) ;
                        if( $validator instanceof BaseValidator )
                        {
                            $this->clean( $validator, $propName );

                            // try the post validator if it exists.
                            $postValidator = $this->getPostValidator( $propName ) ;
                            if( $postValidator instanceof BaseValidator )
                            {
                                $this->clean( $postValidator, $propName );
                            }
                        }
                        else
                        {
                            $init = array(
                                'field'   => $propName,
                                'message' => 'The field "' . $propName . '" has no validator setted!'
                            ) ;
                            $this->errors[] = new ErrorFieldVO( $init ) ;
                        }
                    }
                    catch( Exception $e )
                    {
                        $init = array(
                            'field'   => $propName,
                            'message' => $e->getMessage()
                        ) ;
                        $this->errors[] = new ErrorFieldVO( $init ) ;
                    }
                }
            }
            $this->afterValidate($reflection);

            return $this->hasErrors() === false ;
        }

        /**
         * After validate all fields, we validate the schema if schema validators are setted.
         * Override this method to customize the validation
         *
         * @param  ReflectionClass $reflection
         * @return void
         */
        protected function afterValidate( ReflectionClass $reflection = null)
        {
            if( count( $this->schemaValidators ) > 0 )
            {
                // init the reflection of the vo if not setted.
                if( $reflection === null )
                {
                    $reflection = new ReflectionClass( $this->vo );
                }

                // loop in the schema validators array to validate all.
                foreach( $this->schemaValidators as $schemaValidator )
                {
                    try
                    {
                        if( $schemaValidator instanceof FieldsCompareValidator )
                        {
                            $leftField   = $schemaValidator->getOption(FieldsCompareValidator::$leftFieldKey);
                            $leftValue   = $reflection->hasProperty($leftField) ? $this->vo->$leftField : '' ;
                            $rightField  = $schemaValidator->getOption(FieldsCompareValidator::$rightFieldKey);
                            $rightValue  = $reflection->hasProperty($rightField) ? $this->vo->$rightField : '' ;
                            $cleanValues = $schemaValidator->clean( array( $leftField => $leftValue, $rightField => $rightValue) );
                        }
                        else
                        {
                            throw new InvalidArgumentException( 'The validator must be an instance of FieldsCompareValidator' );
                        }
                    }
                    catch( Exception $e )
                    {
                        $init = array(
                            'message' => $e->getMessage()
                        ) ;
                        $this->globalErrors[] = new ErrorVO( $init ) ;
                    }
                }
            }
        }

        /**
         * Invoked before the validate method.
         * Override this method to customize the validation
         *
         * @return void
         */
        protected function beforeValidate()
        {
        }

        /**
         * Configure the validation of this model.
         *
         * @param  array $exludeFields
         * @return void
         */
        protected function configure( $exludeFields = array() )
        {
            if( !empty( $exludeFields ) )
            {
                $this->setExcludeFields( $exludeFields ) ;
            }
            $this->setValidator( self::ID_FIELD, new IntegerValidator( array( IntegerValidator::$minKey => 1 ) ) ) ;
        }

        /**
         * Try to launch the clean method of the validator.
         *
         * @param  BaseValidator $validator
         * @param  string        $propName
         * @return void
         */
        private function clean( BaseValidator $validator, $propName )
        {
            if( $validator instanceof DatabaseValidator )
            {
                $fields = $validator->getOption( DatabaseValidator::$fieldKey );
                if( is_array( $fields ) )
                {
                    $values = array();
                    foreach( $fields as $field )
                    {
                        $values[$field] = $this->vo->$field;
                    }
                    $cleanValues = $validator->clean( $values );
                    foreach( $cleanValues as $field => $value )
                    {
                        $this->vo->$field = $value;
                    }
                }
                elseif( (is_string( $fields ) || is_numeric( $fields )) && $fields == $propName )
                {
                    $this->vo->$propName = $validator->clean( $this->vo->$propName );
                }
                else
                {
                    throw new InvalidArgumentException( 'We must pass an array or an alphanumeric value in this validator: ' . $propName );
                }
            }
            elseif( $validator instanceof FileValidator )
            {
                $file = $validator->clean( $this->vo->$propName );
                if( $file instanceof ValidatedFile )
                {
                    $fileName = $file->save();
                    if( $file->isSaved() )
                    {
                        $this->vo->$propName = $fileName ;
                    }
                    else
                    {
                        throw new RuntimeException( 'The file "' . $file->getNameFromOriginal() . '" hasn\'t been uploaded!' );
                    }
                }
                elseif( in_array( $file, array( null, '', array() ), true ) ) // not required return
                {
                    $this->vo->$propName = null;
                }
                else
                {
                    throw new InvalidArgumentException( 'We must returned a ValidatedFile for the validator: ' . $propName );
                }
            }
            else
            {
                $this->vo->$propName = $validator->clean( $this->vo->$propName );
            }
        }
    }
?>